package java_concurrency_program_design_in_practice.atomic_reference;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 无锁的对象引用<br/>
 * 它可以保证你在修改对象引用时的安全性<br/>
 * @author lixiangke
 * @date 2017/12/8
 */
public class AtomicReferenceDemo {
    static AtomicReference<Integer> money = new AtomicReference<>(19);

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            new Thread() {
                @Override
                public void run() {
                    while (true) {
                        while (true) {
                            Integer m = money.get();
                            if (m < 20) {
                                if (money.compareAndSet(m, m + 20)) {
                                    System.out.println("余额小于20, 余额充值成功, 余额: " + money.get());
                                    break;
                                }
                            } else {
                                //System.out.println("余额大于20元, 无需充值");
                                break;
                            }
                        }
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        }

        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    while (true) {
                        Integer m = money.get();
                        if (m > 10) {
                            if (money.compareAndSet(m, m - 10)) {
                                System.out.println("大于10元, 消费10元");
                                break;
                            }
                        } else {
                            System.out.println("没有足够余额");
                            break;
                        }
                    }
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

}
